#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project ：uitest 
# @Author  : hpc
# @File    : case.py
# @Time    : 2021/6/13 8:55 下午
import time
import json
import requests
from jira import config
from jira import login


class Jira(object):
    url = config.URL
    headers = config.HEADERS
    cookies = login.Login().jira_login(config.USERNAME, config.PASSWORD)

    def __init__(self):
        self.all_project = self.get_all_project()

    def add_case(self, project, issue_type, summary, description, path, steps):
        """
        @param project:
        @param issue_type:
        @param summary:
        @param description:
        @param path:
        @param steps:
        @return:
        """
        self.headers["Content-Type"] = "application/json;charset=UTF-8"
        self.headers["Cookie"] = self.cookies
        headers = {
            "Content-Type": "application/json;charset=UTF-8",
            'Cookie': self.cookies
        }
        prefix_url = self.url + "/rest/api/2/issue"

        json = {
            "fields": {
                "summary": summary,
                "issuetype": {
                    "id": issue_type
                },
                "project": {
                    "id": project
                },
                "description": description,
                "customfield_10831": path,
                "customfield_10825": steps
            }
        }
        try:
            res = requests.post(url=prefix_url, headers=headers, json=json)
            if res.status_code == 201:
                print(res.text)
                return 200, res.text
            print("导入失败，失败code：{},失败原因：{}".format(res.status_code, res.text))
            return 400, "用例标题：{},导入失败".format(summary)
        except Exception as error:
            print(str(error))

    def sync_zt_case(self, test_cases):
        """同步用例至jira
        :return:
        """
        try:
            for index, case in enumerate(test_cases, 1):
                print('test_case_num:{} 用例标题:{}'.format(index, case.get("fields").get("summary")))
                fields = case.get("fields")
                return self.add_case(fields.get("project").get("id"), fields.get("issuetype").get("id"),
                                     fields.get("summary"), fields.get("description"), fields.get("customfield_10831"),
                                     fields.get("customfield_10825"))
        except Exception as error:
            print(str(error))

    def get_all_project(self):
        headers = {
            "Accept": "application/json, text/javascript, */*; q=0.01",
            "Cookie": self.cookies,
        }
        prefix_url = self.url + "/rest/api/1.0/menus/browse_link?inAdminMode=false&_={}&t=json".format(
            int(round(time.time() * 1000)))
        try:
            res = requests.get(url=prefix_url, headers=headers)
            if res.status_code == 200:
                items = json.loads(res.text).get("sections")
                # 获取所有项目
                project = [i for item in items for i in item.get("items")]
                all_project = []
                for p in project:
                    # 项目id
                    url = p.get("iconUrl") if p.get("iconUrl") else ""
                    pid = url.split("?pid=")
                    if len(pid) != 2:
                        continue
                    else:
                        project_id = pid[1].split("&")[0]
                        all_project.append({"id": project_id, "name": p.get("label")})
                print(all_project)
                return all_project
        except Exception as error:
            print(str(error))
        return []

    def get_project_id(self, project_name):
        try:
            for project in self.all_project:
                project["name"] = project_name
                return project.get("id")
            return -1
        except Exception as error:
            print(str(error))
        return -1
